// pages/myOrder/myOrder.js
let url_js = require("../../utils/url.js");
var common_js = require("../../utils/common.js");
var const_js = require("../../utils/const.js");
var user_js = require("../../utils/user.js");
var sys_js = require("../../utils/system.js");
var ubt_js = require("../../utils/ubt.js");
var name_js = require("../../utils/ubtButtonName.js");
var api = require("../../utils/apiRequest.js");

Page({

  /**
   * 页面的初始数据
   */
  //contentStatus 未请求数据0，有订单1 无订单2
  data: {
    sysInfo: null,
    userInfo: null,
    noOrderUrl: url_js.imgUrl + "no_order.png",
    contentStatus: -1,
    moveLineStartLeft: 0,
    animationData: {},
    segSelectedIndex: 0,
    animation: null,
    statusList: [0, 1, 3, 10, 6],
    selctedOrderInfo: {
      pageInfo: {
        curPage: 1,
        pageSize: 10,
        noMore: false
      },
      itemList: []
    },
    orderList: [], //存放所有的状态的订单
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    //业务埋点
    ubt_js.myPageView(common_js.currentPageName(), options);
    //0.禁止转发
    wx.hideShareMenu();
    //1.初始化数据
    this.initData(options);
    //2.获取屏幕信息
    this.getSystemInfo();
    //3.请求数据
    this.requestToGetOrderList(this.data.selctedOrderInfo.pageInfo.curPage, this.data.selctedOrderInfo.pageInfo.pageSize, this.data.statusList[this.data.segSelectedIndex]);
  },

  //获取屏幕信息
  getSystemInfo: function() {
    if (this.data.sysInfo) {
      var moveLineL = this.data.sysInfo.screenWidth / 10.0 - 24;
      this.setData({
        moveLineStartLeft: moveLineL,
      });
    } else {
      wx.getSystemInfo({
        success: res => {
          //处理滚动条的位置
          var systemInfo = res;
          var moveLineL = systemInfo.screenWidth / 10.0 - 24;
          this.setData({
            moveLineStartLeft: moveLineL,
            sysInfo: systemInfo
          });
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    // 业务埋点
    ubt_js.myPageViewOut(common_js.currentPageName());
  },

  //初始化数据
  initData: function(op) {
    //1.更新userInfo
    let tempUserInfo = user_js.userInfo();
    var tmpSegSelectedIndex = op.segIndex ? op.segIndex : 0;
    this.setData({
      segSelectedIndex: tmpSegSelectedIndex,
      userInfo: tempUserInfo,
      sysInfo: sys_js.systemInfo()
    });

    if (op.segIndex) {
      this.moveLineWithIndex(op.segIndex);
    }
  },

  //请求获取数据
  requestToGetOrderList: function(curPage, pageSize, status, pullDownRefresh) {
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      curPage: curPage,
      pageSize: pageSize,
      status: status,
      shopId: this.data.userInfo.ztd.id
    }
    api.wxRequest(url_js.orderListUrl, data).then(res => {
      this.handleOrderListData(res, curPage, status, pullDownRefresh);
      common_js.hidePageLoading(pullDownRefresh);
    }).catch(err => {
      common_js.hidePageLoading(pullDownRefresh);
      common_js.log(err);
    });
  },

  //处理返回的订单列表数据
  handleOrderListData: function(res, curPage, status, pullDownRefresh) {
    //设置数据
    var tmpList = res.result;
    var tmpOrderMap = new Map(this.data.orderList);
    if (pullDownRefresh) {
      tmpOrderMap.delete(status);
    }

    //全部为0，返回
    if (status == 0 && tmpList.length == 0) {
      this.setData({
        contentStatus: 2
      });
      return;
    }

    //重新生成
    var tmpSelectedInfo = {};
    tmpSelectedInfo.pageInfo = {};
    tmpSelectedInfo.pageInfo.curPage = curPage;
    tmpSelectedInfo.pageInfo.pageSize = 10;
    tmpSelectedInfo.pageInfo.noMore = false;
    tmpSelectedInfo.itemList = [];

    if (res.page.pages <= curPage) {
      tmpSelectedInfo.pageInfo.noMore = true;
    } else {
      tmpSelectedInfo.pageInfo.curPage++;
    }

    if (tmpOrderMap.get(status)) {
      tmpSelectedInfo.itemList = tmpOrderMap.get(status).itemList;
    }
    if (tmpList.length > 0) {
      tmpSelectedInfo.itemList = tmpSelectedInfo.itemList.concat(tmpList);
    }

    tmpOrderMap.set(status, tmpSelectedInfo);
    this.setData({
      selctedOrderInfo: tmpSelectedInfo,
      contentStatus: 1,
      orderList: [...tmpOrderMap]
    });
  },

  //获取请求的pageInfo
  requestPageInfo: function() {
    var tmpPageInfo = {};
    tmpPageInfo.pageInfo = {};
    tmpPageInfo.pageInfo.curPage = 1;
    tmpPageInfo.pageInfo.pageSize = 10;
    tmpPageInfo.pageInfo.noMore = false;
    tmpPageInfo.itemList = [];
    return tmpPageInfo;
  },

  //取消订单
  requestToOrderCancel: function(orderId, status, index) {
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      orderId: orderId,
      shopId: this.data.userInfo.ztd.id
    }
    api.wxRequest(url_js.orderCancelUrl, data).then(res => {
      this.handleOrderCancelData(res, orderId, status, index);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理取消订单的数据
  handleOrderCancelData: function(res, orderId, status, index) {
    common_js.showToast("订单已取消");
    //更新数据
    this.onPullDownRefresh();
  },

  //删除订单
  requestToOrderDelete: function(orderId, status, index) {
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      orderId: orderId,
      shopId: this.data.userInfo.ztd.id
    }
    api.wxRequest(url_js.orderDeleteUrl, data).then(res => {
      this.handleOrderDeleteData(res, orderId, status, index);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理删除订单的数据
  handleOrderDeleteData: function(res, orderId, status, index) {
    //更新展示的状态
    var tmpMap = new Map(this.data.orderList);
    //便利其他的状态数组，如果有相同的id,删除tmpMap.id
    this.data.statusList.forEach(item => {
      if (item != status) {
        tmpMap.delete(item);
      }
    });

    var tmpSelectdInfo = this.data.selctedOrderInfo;
    tmpSelectdInfo.itemList.splice(index, 1);
    tmpMap.set(status, tmpSelectdInfo);

    this.setData({
      selctedOrderInfo: tmpSelectdInfo,
      orderList: [...tmpMap]
    });

    //提示
    common_js.showToast("订单已删除");
  },

  //生成预支付订单
  requestToPayPrepare: function(orderId, status, index) {
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      orderId: orderId,
      shopId: this.data.userInfo.ztd.id,
    }
    api.wxRequest(url_js.payPrepareUrl, data).then(res => {
      this.handlePayPrepareData(res, orderId, status, index);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理生成预支付订单数据
  handlePayPrepareData: function(res, orderId, status, index) {
    var payItem = res.result;
    //微信支付
    wx.requestPayment({
      timeStamp: payItem.timeStamp,
      nonceStr: payItem.nonceStr,
      package: payItem.package,
      signType: payItem.signType,
      paySign: payItem.paySign,
      success: res => {
        //刷新页面
        this.onPullDownRefresh();
      },
      fail: res => {
        if (common_js.containsKeyString(res.errMsg, "fail cancel")) {
          //什么也不做
        } else {
          common_js.showToast(res.errMsg);
        }
      }
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    if (this.data.contentStatus != 1) {
      wx.stopPullDownRefresh();
      return;
    }

    var tmpStatus = this.data.statusList[this.data.segSelectedIndex];
    var tmpPageInfo = this.requestPageInfo();
    //request
    this.requestToGetOrderList(tmpPageInfo.pageInfo.curPage, tmpPageInfo.pageInfo.pageSize, tmpStatus, true);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    if (this.data.selctedOrderInfo.pageInfo.noMore) return;

    this.requestToGetOrderList(this.data.selctedOrderInfo.pageInfo.curPage, this.data.selctedOrderInfo.pageInfo.pageSize, this.data.statusList[this.data.segSelectedIndex]);
  },

  //去逛逛
  gotoBuy: function(e) {
    wx.switchTab({
      url: '../category/category'
    });
  },

  //顶部切换
  onseg: function(e) {
    var index = parseInt(e.currentTarget.dataset.index);
    this.moveLineWithIndex(index);

    var tmpStatus = this.data.statusList[index];
    var tmpOrderMap = new Map(this.data.orderList);
    var orderItem = tmpOrderMap.get(tmpStatus);
    if (orderItem) {
      this.setData({
        selctedOrderInfo: orderItem
      });
    } else {
      //
      var tmpPageInfo = this.requestPageInfo();
      //request
      this.requestToGetOrderList(tmpPageInfo.pageInfo.curPage, tmpPageInfo.pageInfo.pageSize, tmpStatus);
    }

    //回到顶部
    wx.pageScrollTo({
      scrollTop: 0
    });
  },

  moveLineWithIndex: function(index) {
    if (!this.data.animation) {
      var animation = wx.createAnimation({
        timingFunction: 'ease',
      });
      this.setData({
        animation: animation
      });
    }
    var translateX = (this.data.sysInfo.screenWidth / 5.0) * index;
    this.data.animation.translateX(translateX).step();
    this.setData({
      segSelectedIndex: index,
      animationData: this.data.animation.export()
    });
  },

  //去支付
  onBuy: function(e) {
    var index = e.currentTarget.dataset.index;
    var item = this.data.selctedOrderInfo.itemList[index];
    var tmpStatus = this.data.statusList[this.data.segSelectedIndex];
    this.requestToPayPrepare(item.id, tmpStatus, index);
  },

  //删除订单
  onDelete: function(e) {
    var index = e.currentTarget.dataset.index;
    var item = this.data.selctedOrderInfo.itemList[index];
    var tmpStatus = this.data.statusList[this.data.segSelectedIndex];

    this.requestToOrderDelete(item.id, tmpStatus, index);
  },

  //取消订单
  onCancel: function(e) {
    var index = e.currentTarget.dataset.index;
    var item = this.data.selctedOrderInfo.itemList[index];
    var tmpStatus = this.data.statusList[this.data.segSelectedIndex];
    common_js.showModal("是否确认取消订单？", null, true, "放弃", "取消订单", () => {
      this.requestToOrderCancel(item.id, tmpStatus, index);
    });
  },

  //售后
  onAfterSale: function(e) {
    var index = e.currentTarget.dataset.index;
    var item = this.data.selctedOrderInfo.itemList[index];
    wx.navigateTo({
      url: '../myOrderAfterSaleDetail/myOrderAfterSaleDetail?orderId=' + item.id
    })
  },

  //点击列表
  onItem: function(e) {
    var index = e.currentTarget.dataset.index;
    var item = this.data.selctedOrderInfo.itemList[index];
    wx.navigateTo({
      url: '../myOrderDetail/myOrderDetail?orderId=' + item.id + '&status=' + this.data.statusList[this.data.segSelectedIndex]
    });
  }
})